#include "SDLApplication.h"

extern bool appRunning;

SDLApplication::SDLApplication(void)
{
	SDL_Init(SDL_INIT_EVERYTHING);
	screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE | SDL_OPENGL | SDL_FULLSCREEN);

	init();
	currentScene = new Scene();
	currentScene->setSkyBox(new SkyBox("D:\\Resources\\SkyBox1\\"));
	currentScene->setCamera(new Camera(), 0, 2.f, 5.f);
	currentScene->setTerrain(new ObjTerrain("D:\\Resources\\ObjTerrain\\hmap.obj"));
}

SDLApplication::~SDLApplication(void)
{
	SDL_Quit();
}

void SDLApplication::init()
{
	glClearColor(0.0, 0.0, 0.0, 1.0);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45, 640.0/480.0, 1.0, 5000.0);
	glMatrixMode(GL_MODELVIEW);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_TEXTURE_2D);
}

void SDLApplication::run()
{
	while (appRunning == true)
	{
		time = SDL_GetTicks();
		while (SDL_PollEvent(&evt))
		{
			switch (evt.type)
			{
			case SDL_QUIT:
				appRunning = false;
				break;
			case SDL_KEYDOWN:
				KeyManager::get()->injectKeyDown(evt.key.keysym.sym);
				break;
			case SDL_KEYUP:
				KeyManager::get()->injectKeyUp(evt.key.keysym.sym);
				break;
			}
		}

		if (currentScene) currentScene->render();

		SDL_GL_SwapBuffers();
		if (1000/30 > (SDL_GetTicks() - time))
			SDL_Delay (1000/30 - (SDL_GetTicks() - time));
	}
}
